<template>
	<view class="login">
		<!-- #ifndef H5 -->
		<UniNavBar title="登录" :statusBar="true" :border="false" @clickLeft="leftBack" leftIcon="back"></UniNavBar>
		<!-- #endif -->
		<view class="header">
			<view class="logo" @click="codeLock(1)">
				<image
					src="https://erised-fresh.oss-cn-shenzhen.aliyuncs.com/592800/0tcFZPuDLYmnaa2ae8e7029f07de28acfc7434c9c518.png"
					mode=""></image>
			</view>
			<view class="title" @click="codeLock(2)">
				<view>{{register?'账号注册':'Hi~'}}</view>
				<view>欢迎使用梯无忧维保端</view>
			</view>
		</view>
		<block v-if="!codeShow">
				<view class="loginforms"> 
					<view class="form_conten">
						<input class="cphone" @input="phoneInput" v-model="form.username" type="number" placeholder="请输入手机号" />
						<view class="error" :class="error ? 'error show' : 'error'">{{ error }}</view>
						<view class="codepass">
							<!-- <input v-if="tabShow" class="cpassword" type="password"  placeholder="请输入密码"  /> -->
							<input class="cpassword" @blur="codeblurs" v-model="form.codes" placeholder="请输入验证码" />
							<view class="codep" v-if="!codeStatus" @click="getCodeClick">获取验证码</view>
							<view :class="['codep', codeStatus ? 'codepTime' : '']" v-else>{{ countTime }} </view>
						</view>
						<view class="error" :class="codeError ? 'error show' : 'error'">{{ codeError }}</view>
					</view>
					<view class="btn" @click="hanleLogin">登录</view>
					<view class="agreement">
						<view class="radios" @click="agree = !agree">
							<view :class="agree ? 'radio agree' : 'radio'">
								<view class=""></view>
							</view>
							<text>我已阅读并同意</text>
						</view>
						<text class="link" @click="toAgreement">《{{ configs.appName }}用户协议》</text>
					</view>
				</view>
		</block>
				<!-- 测试人员隐藏登入 -->
		<block v-else>
				<view class="login-form" v-if="!showPassword">

					<view class="account input">
						<input type="number" @input="phoneInput" maxlength="11" v-model="form.username" placeholder="请输入手机号"
							placeholder-style="color: #ccc;font-weight: normal;" />
						<view class="error" :class="error ? 'error show' : 'error'">{{ error }}</view>
					</view>

					<view :class="nextDisabled ? 'next disabled' : 'next'" @click="showPasswordFuc()">
						<image src="/static/images/next_w.png" mode=""></image>
					</view>
				</view>

				<view class="login-form" v-else>
					<view class="account input">
						<input type="text" v-model="form.tenantId" placeholder="租户id"
							placeholder-style="color: #ccc;font-weight: normal;" />

					</view>

					<view class="account input">
						<input v-if="eye" type="text" v-model="form.password" placeholder="请输入密码"
							placeholder-style="color: #ccc;font-weight: normal;" />
						<input v-else type="password" v-model="form.password" placeholder="请输入密码"
							placeholder-style="color: #ccc;font-weight: normal;" />
						<image @click.stop="eye = !eye"
							:src="eye ? '/static/images/eye-open.png' : '/static/images/eye-close.png'" mode="">
						</image>
						<view class="error" :class="error ? 'error show' : 'error'">{{ error }}</view>
						<text class="forget" @click="forgotPasswordFuc">忘记密码</text>
					</view>

					<view :class="(form.password.length < 6 || !agree) ? 'btn pawDisabled' : 'btn'" @click="hanleLoginCode">登录
					</view>

					<view class="agreement">
						<view class="radios" @click="agree = !agree">
							<view :class="agree ? 'radio agree' : 'radio'">
								<view class="">

								</view>
							</view>
							<text>同意</text>
						</view>
						<text class="link" @click="toAgreement">《{{ configs.appName }}用户协议》</text>
					</view>
				</view>
		</block>

				<!-- 重置秘密 -->
		<neil-modal :show="forgotPassword" @close="closeModal" :show-cancel="false" confirmText="好的, 我知道了"
				confirmColor="#fff" confirmBgColor="#0091ff" @confirm="closeModal">
				<view class="modelView">
					<view>如需重置密码, 请致电管理员</view>
					<view class="modlePhone" @click="callPhoneNum('0760-88789898')">0760-88789898</view>
				</view>
				</neil-modal>
				<!-- 登录失败模态框 -->
				<neil-modal :show="failLogin" @close="hanleCloseFailLogin" :show-cancel="false" confirmColor="#fff"
				confirmBgColor="#0091ff" confirmText="好的, 我知道了" @confirm="failLogin = false">
				<view class="modelView">
					<view>{{ msg }}</view>
					<view>
						如有需要,请致电
						<view class="modlePhone" @click="callPhoneNum('0760-88789898')">0760-88789898</view>
					</view>
				</view>
		</neil-modal>

		<div class="phone_tips" v-if="!register">
			仅对维保公司人员开放,登录需要获取您的手机号用于唯一性识别和短信验证登录。
		</div>
		 
	</view>
</template>

<script>
// import configObj from '@/utils/config.js';
import UniNavBar from '@/components/uni-nav-bar/uni-nav-bar.vue';
import neilModal from '@/components/neil-modal/neil-modal.vue';
import md5 from 'js-md5';
import { login, userLogin, checkPhone, setWxOpenid,  getCodeNetworkApi, getUserMessage, getTenantInfoByPhone } from '@/apis/login.js';
import {  hanleToken } from '@/utils/utils.js';
export default {
	components: { neilModal, UniNavBar },
	data() {
		return {
			msg: '',
			phone: '',
			forgotPassword: false,
			failLogin: false,
			form: {
				username: '',
				password: '',
				tenantId: ''
			},
			type: 0,
			nextDisabled: true,
			error: '',
			showPassword: false,
			pawDisabled: true,
			agree: false,
			eye: false,
			// /////////////
			tabShow: false,
			timers: null,
			countTime: '',
			codeStatus: false,
			codeError: '',
			// 验证码
			codeData: {},
			openID: null,
			// 用于测试调试
			count: 0,
			// 用于测试调试
			codeShow: false,
			// 注册模式(app 用
			register:false
		};
	},
	computed:{
		configs() {
			return this.$config;
		}
	},
	onLoad(res) {
		this.type = res.type;
		this.openID = res.openid || null;
		if (res.register) {
			this.register = true;
			this.form.tenantId = 388475;
		}
		console.log(res.type);
	},
	methods: {
		// 顶部导航栏返回
		leftBack() {
			uni.navigateBack();
		},
		// 切换密码登入
		switchTitle(type) {
			this.tabShow = false;
			if (type === 'pass') {
				this.tabShow = true;
			}
		},
		// 获取验证码
		getCodeClick() {
			let phone = this.form.username;
			if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(phone)) {
				this.error = '请输入格式正确的手机号';
				return;
			}
			if (!this.tabShow) {
				getCodeNetworkApi({
					phone: this.form.username,
				}).then(res => {
					if (res.code === 200) {
						this.codeData = res.data || {};
						this.codeStatus = true;
						this.getCodeNetwork();
					} else {
						this.codeStatus = false;
					}
				}).catch(() => {
					this.codeStatus = false;
					uni.showModal({
						title: '提示',
						content: '手机号尚未加入通讯录无法登入,请联系公司负责人添加您的信息。',
						success: function (res) {
							if (res.confirm) {
								console.log('用户点击确定');
							}
						}
					});
					// uni.showToast({
					// 	title: err.msg,
					// 	icon: 'none'
					// });
				});
			}
		},
		// 验证码倒计时
		getCodeNetwork() {
			var hTime = 59;
			this.countTime = '重新获取(59)';
			this.timers = setInterval(() => {
				if (hTime <= 0) {
					this.countTime = '获取验证码';
					this.codeStatus = false;
					clearInterval(this.timers);
					return;
				}
				this.countTime = '重新获取(' + hTime + ')';
				hTime--;
			}, 1000);
		},
		// 获取验证码输入
		codeblurs(e) {
			console.log('验证', e);
			let val = e.detail.value || 0;
			if (!val) {
				this.codeError = '请输入验证码';
			} else {
				if (!/^[0-9]{6}$/g.test(val)) {
					this.codeError = '请输入正确验证码';
				} else {
					this.codeError = '';
				}
			}
		},
		// 查询手机号拥有的公司列表
		getPhoneList(phone) {
			return new Promise((resolve, reject) => {
				getTenantInfoByPhone({ phone }).then(res => {
					if (res.code === 200) {
						resolve(res.data);
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
						reject(false);
					}
				});
			});
		},
		// 查询手机号是否有权限
		checkPhone() {
			uni.showLoading({
				title: '校验中',
				mask: true
			});
			// let _this = this;
			checkPhone(this.form.username)
				.then(() => { })
				.then(() => {
					this.nextDisabled = false;
					this.showPassword = true;
					uni.hideLoading();
				})
				.catch(err => {
					if (err && err.errMsg) {
						this.error = '网络请求出错,请检查联网状态';
					} else {
						this.error = '您的手机号未加入，请联系贵司相关负责人添加';
					}

					// this.nextDisabled = true;
				});
		},

		// 显示输入密码
		showPasswordFuc() {
			if (this.nextDisabled) {
				if (this.error) {
					uni.showToast({
						title: this.error,
						icon: 'none'
					});
				}

				return;
			} else {
				this.checkPhone();
			}
		},

		// 输入手机号
		phoneInput(res) {
			let phone = res.detail.value;
			if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(phone)) {
				this.error = '请输入格式正确的手机号';
				this.nextDisabled = true;
			} else {
				this.error = '';
				this.nextDisabled = false;
				// this.checkPhone();
			}
		},
		// 忘记密码
		forgotPasswordFuc() {
			uni.navigateTo({
				url: '/pageModules/mine/setPassword?phone=' + this.form.username,
			});

			return;
		},

		callPhoneNum(phone) {
			console.log(phone);
			uni.makePhoneCall({
				phoneNumber: phone
			});
		},
		handleForget() {
			this.forgotPassword = true;
		},
		closeModal() {
			this.forgotPassword = false;
		},

		// 登录
		async hanleLogin() {
			if (this.register) {
				this.hanleLoginCode();
				return;
			}
			// let _this = this;
			const { username, codes } = this.form;
			// if (!password) {
			// 	uni.showToast({
			// 		title: '请输入6位数以上的密码',
			// 		icon: 'none'
			// 	});
			// 	return
			// }  
			if (!username) {
				this.error = '请输入手机号';
				return;
			}
			if (!codes) {
				this.codeError = '请输入验证码';
				return;
			}
			if (!this.agree) {
				uni.showToast({
					title: '同意协议后才才可以登录',
					icon: 'none'
				});
				return;
			}
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			// var phoneList = await this.getPhoneList(username) || []

			// // hanleToken('set', 'userCompanyInfo', phoneList);

			// let tenantId = phoneList[0].tenantId

			const params = {
				grant_type: 'phone',
				scope: 'all',
				phone: username,
				// tenantId,
				id: this.codeData.id,
				value: codes
			};
			getUserMessage(params, this.codeData.id)
				.then(async res => {
					if (res.code === 200) {
						uni.hideLoading();
						uni.setStorage({ key: 'userCompanyInfo', data: res.data });
						if (res.data.length <= 0) {
							uni.showModal({
								title: '提示',
								content: '手机号尚未加入通讯录无法登入,请联系公司负责人添加您的信息。',
								success: function (res) {
									if (res.confirm) {
										console.log('用户点击确定');
									}
								}
							});
							return;
						}
						if (res.success) {
							// 如果单公司单角色不需要跳转到切换角色页面
							if (res.data.length == 1 && res.data[0].roleList.length == 1) {
								this.codeLogin(res.data[0], username);
								return;
							}
							uni.redirectTo({
								url: '/pages/login/companySelect?phone=' + username + '&type=' + this.type
							});
							return;
						}
						uni.showToast({
							title: '验证码错误',
							icon: 'none'
						});
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				})
				.catch(err => {
					console.log('err', err);
					uni.showToast({
						title: err,
						icon: 'none'
					});
				});
		},

		// 验证码登录
		codeLogin(obj, phone) {
			const params = {
				grant_type: 'phone',
				scope: 'all',
				username: phone,
				password: obj.verificationKey,
				tenantId: obj.tenantId,
			};
			uni.showLoading({
				title: '登录中'
			});
			userLogin(params)
				.then(async res => {
					console.log(res, '登录接口');
					if (res.code === 200) {
						uni.hideLoading();

						uni.showToast({
							title: '登录成功',
							icon: 'none'
						});
						hanleToken('set', 'token', res.data.token_type + ' ' + res.data.access_token);
						hanleToken('set', 'refresh_token', res.data.refresh_token);
						hanleToken('set', 'userData', res.data);
						this.setWxOpenid(obj.userId);
						this.$store.commit('user/setUserinfo', res.data);
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/home/index'
							});
						}, 200);
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				})
				.catch(err => {
					console.log('err', err);
					uni.showToast({
						title: err,
						icon: 'none'
					});
					uni.showModal({
						title: '提示',
						content: '登录失败',
						showCancel: false,
						success() {

						}

					});
				});
		},

		// 更新微信openid
		setWxOpenid(userId) {
			uni.login({
				success: res => {
					setWxOpenid({
						appid: this.configs.appId,
						code: res.code,
						userId
					}).then(() => { });
				},
				fail() { }
			});
		},

		// 用于测试人员的隐藏开关登入
		codeLock(lock) {
			// if(configObj.baseUrl.indexOf("com") != -1 ){//生产环境取消隐藏测试口
			// 	return
			// }
			this.count += 1;
			if (lock === 1 && this.count === 5) {
				this.codeShow = true;
				return;
			}
			if (lock === 2) {
				this.count = 0;
				this.codeShow = false;
			}
		},
		// 用于测试人员的隐藏开关登入
		hanleLoginCode() {
			// let _this = this;

			let { username, password, tenantId } = this.form;
			if (this.register) {
				username = '13800138005';
				password = '123456';
				tenantId = '388475';
			}
			if (!password) {
				uni.showToast({
					title: '请输入6位数以上的密码',
					icon: 'none'
				});

				return;
			}
			if (!this.agree) {
				uni.showToast({
					title: '同意协议后才才可以登录',
					icon: 'none'
				});

				return;
			}
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			const params = {
				grant_type: 'password',
				scope: 'all',
				username,
				tenantId: this.form.tenantId,
				password: md5(password)
			};
			login(params)
				.then(async res => {
					console.log(res, '登录接口');
					if (res.code === 200) {
						hanleToken('set', 'token', res.data.token_type + ' ' + res.data.access_token);
						hanleToken('set', 'refresh_token', res.data.refresh_token);
						hanleToken('set', 'userData', res.data);
						const { username } = this.form;
						let phoneList = await this.getPhoneList(username) || [];
						// console.log(phoneList,"phoneList的值")
						let roleList = phoneList.filter(item => item.tenantId == tenantId);
						console.log(roleList, 'roleList');
						// hanleToken('set', 'userCompanyInfo', roleList);
						uni.setStorage({ key: 'userCompanyInfo', data: roleList });
						this.$store.commit('user/setUserinfo', res.data);
						uni.showToast({
							title: '登录成功',
							icon: 'none'
						});
						if (this.register) {
							uni.reLaunch({
								url: '/pages/home/index'
							}); 
							return;
						}
						// 判断是否单角色
						if (roleList[0].roleList.length === 1) {
							setTimeout(() => {
								uni.reLaunch({
									url: '/pages/home/index'
								}); 
							}, 200);
						} else {
							uni.redirectTo({
								url: '/pages/login/companySelect?phone=' + username
							});
						} 
					}
				})
				.catch(err => {
					console.log('err', err);
					this.error = '密码错误，请重新输入';
				});
		},
		hanleCloseFailLogin() {
			this.failLogin = false;
		},
		handleWxLogin() {
			uni.redirectTo({
				url: '/pages/login/index?type=' + this.type
			});
		},
		toAgreement() {
			uni.navigateTo({
				url: '/pageModules/pubilc/agreement'
			});
		}
	}
};
</script>

<style lang="scss">
.header {
	width: 95%;
	margin: 20rpx auto;
	display: flex;
	align-items: center;
	margin-bottom: 100rpx;

	.logo {
		image {
			width: 144rpx;
			height: 144rpx;
		}
	}

	.title {
		font-size: 34rpx;
		font-family: PingFangSC, PingFangSC-Medium;
		font-weight: bold;
		text-align: left;
		color: #3b3b3b;

		view:nth-child(1) {
			font-size: 44rpx;
		}
	}
}

.placeholder {
	color: #ccc;
	font-weight: normal;
}

.loginforms {
	width: 680rpx;
	margin: 0 auto;

	.form_title {
		display: flex;
		flex-direction: row;
		justify-content: center;
		width: 100%;
		margin-bottom: 40rpx;
		// color: #0091ff;

		.vcode {
			font-size: 28rpx;
			font-weight: 500;
			color: #666666;

			text {
				display: block;
				width: 80rpx;
				margin: 0 auto;
				border-bottom: 4rpx #0091ff solid;
				margin-top: 20rpx;
			}
		}

		.vline {
			margin: 0 40rpx;
			color: #666666;
		}

		.vadmin {
			font-size: 28rpx;
			font-weight: 500;
			color: #666666;

			text {
				display: block;
				width: 80rpx;
				margin: 0 auto;
				border-bottom: 4rpx #0091ff solid;
				margin-top: 20rpx;
			}

		}

		.vact {
			color: #0091ff;
			font-weight: 600;
		}
	}

	.form_conten {
		margin-top: 20rpx;

		// position: relative;
		.cphone {
			width: 620rpx;
			height: 84rpx;
			background: #f3f6f8;
			border-radius: 8rpx;
			padding: 0 30rpx;
		}

		.codepass {
			display: flex;
			flex-direction: row;

			// margin-top: 40rpx;
			.cpassword {
				width: 430rpx;
				height: 84rpx;
				background: #f3f6f8;
				border-bottom-left-radius: 8rpx;
				border-top-left-radius: 8rpx;

				padding: 0 30rpx;
			}

			.codep {
				border-bottom-right-radius: 8rpx;
				border-top-right-radius: 8rpx;
				width: 190rpx;
				height: 84rpx;
				line-height: 84rpx;
				background: #f3f6f8;
				color: #0091ff;
				font-weight: 600;
			}

			.codepTime {
				color: #CCCCCC;
			}
		}

		.error {
			// position: absolute;
			// bottom: -42rpx;
			margin: 10rpx 0;
			font-size: 28rpx;
			opacity: 0;
			transition: 0.3s all;
			text-align: left;
			color: #e02020;
			height: 30rpx;
		}

		.show {
			opacity: 1;
		}
	}

	.btn {
		width: 670rpx;
		height: 84rpx;
		opacity: 1;
		background: #0091ff;
		transition: 0.4s all;
		border-radius: 8rpx;
		margin: 72rpx auto;
		font-size: 28rpx;
		text-align: center;
		line-height: 84rpx;
		margin-bottom: 20rpx;
		color: #fff;
	}

	.agreement {
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		color: #999999;

		.radio {
			width: 20rpx;
			height: 20rpx;
			opacity: 1;
			border: 2rpx solid #979797;
			border-radius: 50%;
			margin-right: 12rpx;
			display: flex;
			justify-content: center;
			align-items: center;

			view {
				width: 12rpx;
				height: 12rpx;
				opacity: 1;
				background: #fff;
				border-radius: 50%;
			}
		}

		.agree {
			border: 2rpx solid #0091ff;

			view {

				background: #0091ff;
			}
		}
	}
}

.login-form {
	width: 100%;
	margin: 0 auto;

	.input {
		width: 660rpx;
		height: 100rpx;
		opacity: 1;
		background: #ffffff;
		border: 2rpx solid #eeeeee;
		border-radius: 8rpx;
		margin: 0 auto;
		position: relative;

		input {
			width: 560rpx;
			height: 100rpx;
			font-size: 36rpx;
			padding: 0 32rpx;
			color: #333;
			font-weight: bold;
		}

		image {
			width: 32rpx;
			height: 32rpx;
			position: absolute;
			right: 30rpx;
			top: 34rpx
		}

		.error {
			position: absolute;
			bottom: -42rpx;
			font-size: 28rpx;
			opacity: 0;
			transition: 0.3s all;
			text-align: left;
			color: #e02020;
		}

		.forget {
			position: absolute;
			bottom: -42rpx;
			font-size: 28rpx;
			color: #0091ff;
			right: 0;
		}

		.show {
			opacity: 1;
		}
	}

	.next {
		width: 112rpx;
		height: 112rpx;
		opacity: 1;
		background: #0091ff;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 72rpx auto;
		transition: 0.4s all;

		image {
			width: 70rpx;
			height: 70rpx;
		}
	}

	.disabled {
		background: #efefef;
	}

	.btn {
		width: 670rpx;
		height: 84rpx;
		opacity: 1;
		background: #0091ff;
		transition: 0.4s all;
		border-radius: 8rpx;
		margin: 72rpx auto;
		font-size: 28rpx;
		text-align: center;
		line-height: 84rpx;
		margin-bottom: 20rpx;
		color: #fff;
	}

	.pawDisabled {
		background: #efefef;
	}

	.agreement {
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		color: #999999;

		.radio {
			width: 20rpx;
			height: 20rpx;
			opacity: 1;
			border: 2rpx solid #979797;
			border-radius: 50%;
			margin-right: 12rpx;
			display: flex;
			justify-content: center;
			align-items: center;

			view {
				width: 12rpx;
				height: 12rpx;
				opacity: 1;
				background: #fff;
				border-radius: 50%;
			}
		}

		.agree {
			border: 2rpx solid #0091ff;

			view {

				background: #0091ff;
			}
		}
	}
}

.link {
	color: #0091ff;
}

.radios {
	display: flex;
	align-items: center;
	padding: 20rpx 0;

}

// #ifdef MP
.phone_tips {
	width: 80%;
	color: #999;
	text-align: center;
	position: absolute;
	bottom: 61rpx;
	left: 10%;
}
// #endif

// #ifdef H5

page {
	height:100%
}

.login{
	// min-height: 480px;
	height: 100%;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	
}

.phone_tips {
	text-align: center;
	color: #999;
	text-align: center;
	margin:17.5px; 
	padding-bottom: 50px;
}
// #endif
</style>
